
interface FileData {
    type: 'file' | 'text';
    content: string;
    source: string;
}

class SaveFile {
    private fileMap: Map<string, FileData[]> = new Map();
    constructor() {
    }

    addTextFile(ip: string, content: string, source: string) {
        const fileData: FileData = {
            type: 'text',
            content,
            source,
        };
        this.fileMap.set(ip, [...(this.fileMap.get(ip) || []), fileData]);
    }

    async addFile(ip: string, file: File, source: string) {

        await Deno.mkdir("./input/" + ip, { recursive: true });
        // 获取文件内容（无论大小，都会读入内存）
        const fileData = await file.bytes();
        const fileNameStrs = file.name.split(".");
        const suffix = "."+fileNameStrs[fileNameStrs.length - 1];
        const prefix = file.name.substring(0, file.name.length - suffix.length);
        const tempFilePath = await Deno.makeTempFile({
            dir: "./input/" + ip,
            prefix,
            suffix,
        });
        await Deno.writeFile(tempFilePath, fileData);

        console.log("Temp file path 3:", tempFilePath);

        this.fileMap.set(ip, [...(this.fileMap.get(ip) || []), {
            type: 'file',
            content: tempFilePath.split('\\')[1],
            source,
        }]);
    }

    getFiles(ip: string): FileData[] {
        return this.fileMap.get(ip) || [];
    }

    async downloadFile(ip: string, fileName: string) {
        const filePath = './input/' + ip + '/' + fileName;
        const fileContent = await Deno.readFile(filePath);
        return fileContent;
    }

    async clearFiles() {
        const dirName = './input/';
        try {
            // 检查 input 目录是否存在
            try {
                await Deno.stat(dirName);
            } catch (err) {
                if (err instanceof Deno.errors.NotFound) {
                    console.log('input 目录不存在，无需清理');
                    return;
                }
                throw err;
            }

            // 遍历 input 目录下的每一项（文件或子目录）
            for await (const dirEntry of Deno.readDir(dirName)) {
                const entryPath = `${dirName}${dirEntry.name}`;
                await Deno.remove(entryPath, { recursive: true });
                console.log(`%c已删除: ${entryPath}`, 'color: green;');
            }

            console.log(`%c✅ 已清空 ${dirName} 下的所有内容`, 'color: green;');
        } catch (e: any) {
            console.log(`%ccleanupTempFiles error: ${e?.message}`, 'color: red;');
        }
    }
}

export default new SaveFile();